﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using BusinessLogicLayer.Manager;
using Objects;
using AutoFix.Base;
using Common;
using System.Text;
using System.IO;
namespace AutoFix
{
    public partial class register : BasePage
    {
        #region [BasePage Implementations]
        /// <summary>
        /// Gets or sets a value indicating whether [is login page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is login page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsLoginPage { get { return false; } }

        /// <summary>
        /// Gets or sets a value indicating whether [is anonymous page].
        /// </summary>
        /// <value>
        ///   <c>true</c> if [is anonymous page]; otherwise, <c>false</c>.
        /// </value>
        protected override bool IsAnonymousPage { get { return true; } }

        /// <summary>
        /// Page name
        /// </summary>
        protected override string PageName
        {
            get { return "Register"; }
        }

        /// <summary>
        /// Gets the authorized user types.
        /// </summary>
        protected override List<UserType> AuthorizedUserTypes
        {
            get { return new List<UserType>(new UserType[] { UserType.Admin, UserType.Contributor, UserType.Guest }); }
        }

        #endregion

        #region [Event Handlers]
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        /// <summary>
        /// Handles the click event of the register button.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnRegister_Click(object sender, EventArgs e)
        {

            UserManager manager = new UserManager();
            User user = new User();
            bool success = false;
            string fileName = string.Empty;
            string file = string.Empty;
            try
            {
                user.FirstName = this.txtFirstName.Text.Trim();
                user.LastName = this.txtLastName.Text.Trim();
                user.EmailAddress = this.txtEmailAddress.Text.Trim();
                user.UserName = this.txtUserName.Text.Trim();
                user.Password = Encryption.Encrypt(this.txtPassword.Text.Trim());
                user.City = this.txtCity.Text.Trim();
                user.Country = ddlCountry.SelectedValue;
                user.PhoneNumber = this.txtPhoneNumber.Text.Trim();
                user.UserTypeID = 3;
                user.IsActive = true;

                if (this.fleProfilePicture.HasFile)
                {
                    if (this.fleProfilePicture.PostedFile.ContentType == "image/jpeg")
                    {
                        Guid guid = Guid.NewGuid();
                        StringBuilder path = new StringBuilder();
                        path.Append(AppConfiguration.UserProfileImagePath);

                        string pathToFile = path.ToString();
                        path = null;
                        string fileToStore = guid + ".jpg";

                        string completeDirectoryPath = Server.MapPath(pathToFile);
                        if (!Directory.Exists(pathToFile))
                        {
                            Directory.CreateDirectory(completeDirectoryPath);
                            completeDirectoryPath = Path.Combine(completeDirectoryPath, fileToStore);
                            if (!File.Exists(completeDirectoryPath))
                            {
                                file = completeDirectoryPath;
                                user.ProfilePictureURL = fileToStore;
                                this.fleProfilePicture.SaveAs(file);
                            }
                        }

                    }
                    else
                    {
                        this.pageActionMessage.InnerText = "Invalid image file. Only jpg format is allowed";
                        this.pageActionMessage.Attributes.Add("class", "error-msg");
                        return;
                    }
                }
                else
                {
                    user.ProfilePictureURL = "";
                }


                success = manager.UpdateUser(user);
                if (success)
                {

                    this.pageActionMessage.InnerText = "Your information was successfully added to the system. Try login to the system.";
                    this.pageActionMessage.Attributes.Add("class", "success-msg");
                }
                else
                {
                    this.pageActionMessage.InnerText = "Failed to add your information to the system";
                    this.pageActionMessage.Attributes.Add("class", "error-msg");
                }
            }
            catch (Exception)
            {
                this.pageActionMessage.InnerText = "Failed to add user to the system";
                this.pageActionMessage.Attributes.Add("class", "error-msg");
            }
            finally
            {
                user = null;
                manager = null;
            }

        } 
        #endregion
    }
}